import { ProForm, ProFormInstance } from '@/components/Pro';
import { deviceManagerControllerGetDeviceModelList } from '@/services/ess/deviceManager';
import { stationAreaControllerImplUpdateStationArea } from '@/services/ess/stationArea';
import { stationSelfDeviceControllerImplUpdateStationDevice as updateDevice } from '@/services/ess/stationDevice';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { CopyOutlined } from '@ant-design/icons';
import { Button, ConfigProvider, Form, Input, message, Select, Space, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

type FieldType = {
  baseInfo: {
    id?: number;
    name?: string;
    model?: string;
    type?: number;
    code?: string;
    areaId?: number;
    voltageLevel?: number;
    voltLevel?: number;
    deviceType?: string | null;
  } | null;
  handleBaseInfo: (res: any) => void;
  fliterTreeData: any[];
};

interface DeviceModelVO {
  deviceId: number;
  deviceModelName: string;
}

interface VoltLevelOption {
  label: string;
  value: string;
}

const App: React.FC<FieldType> = (props) => {
  const { baseInfo, handleBaseInfo } = props;
  const FormRef = useRef<ProFormInstance>();
  const [deviceModelList, setDeviceModelList] = useState<DeviceModelVO[]>([]);
  const [voltLevels, setVoltLevels] = useState<VoltLevelOption[]>([]);

  const fetchDeviceModelList = async (deviceType: number) => {
    try {
      const result = await deviceManagerControllerGetDeviceModelList({ deviceType });
      setDeviceModelList(result.data || []);
    } catch (error) {
      console.error('获取设备型号列表失败', error);
      setDeviceModelList([]);
    }
  };

  useEffect(() => {
    if (baseInfo) {
      const voltLevelValue = baseInfo.voltLevel || baseInfo.voltageLevel;
      FormRef?.current?.setFieldsValue({
        ...baseInfo,
        voltLevel: voltLevelValue ? voltLevelValue.toString() : undefined,
      });
      if (baseInfo.type) {
        fetchDeviceModelList(baseInfo.type);
      }
    } else {
      FormRef?.current?.resetFields();
    }

    // 获取电压等级选项
    fetchDictInfo(DATABASE_TYPE_ENUM.VOLT_LEVEL).then((res) => {
      if (res) {
        const formattedVoltLevels = res.map((item: any) => ({
          label: item.label,
          value: item.value.toString(), // 确保 value 是字符串
        }));
        setVoltLevels(formattedVoltLevels);
      }
    });
  }, [baseInfo]);

  // 类型守卫函数
  const isAreaParams = (params: any): params is { area_id: string } => {
    return 'area_id' in params;
  };

  const handleFinish = async (value: any) => {
    if (!baseInfo) {
      message.error('设备信息不存在');
      return;
    }

    const { id, ...restBaseInfo } = baseInfo;
    if (id === undefined) {
      message.error('设备ID不存在');
      return;
    }

    const isArea = baseInfo.deviceType === 'area';
    const params = isArea ? { area_id: String(id) } : { device_id: String(id) };

    // 查找选中的设备型号的名称并赋值给 model 字段
    const selectedModel = deviceModelList.find((model) => model.deviceId === value.model);
    if (selectedModel) {
      value.model = selectedModel.deviceModelName;
    }

    const body = {
      ...restBaseInfo,
      ...value,
      voltLevel: value.voltLevel ? parseInt(value.voltLevel, 10) : undefined,
    };

    try {
      let result;
      if (isAreaParams(params)) {
        result = await stationAreaControllerImplUpdateStationArea(params, body);
      } else {
        result = await updateDevice(params, body);
      }
      console.log('result', result);
      if (result.success) {
        message.success('修改成功');
        handleBaseInfo(true);
      }
    } catch (error) {
      console.error('更新信息失败', error);
      message.error('修改失败');
    }
  };

  return (
    <div style={{ maxWidth: '600px' }}>
      {baseInfo && (
        <ProForm
          formRef={FormRef}
          layout="horizontal"
          grid={true}
          labelCol={{
            flex: `0 0 120px`,
          }}
          style={{ marginTop: 20 }}
          submitter={{
            render: (props, doms) => (
              <div style={{ paddingLeft: 120 }}>
                <Space>{doms}</Space>
              </div>
            ),
          }}
          onFinish={handleFinish}
          onValuesChange={(changedValues) => {
            if (changedValues.type) {
              fetchDeviceModelList(changedValues.type);
            }
          }}
        >
          {baseInfo.deviceType === 'area' ? (
            <>
              <Form.Item
                name="areaName"
                label="分区名称"
                className="ant-col ant-col-18"
                rules={[{ required: true, message: '请输入分区名称' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="voltLevel"
                label="电压等级"
                className="ant-col ant-col-18"
                rules={[{ required: true, message: '请选择电压等级' }]}
              >
                <Select
                  options={voltLevels}
                  onChange={(value, option) => {
                    console.log('Selected value:', value);
                    console.log('Selected option:', option);
                  }}
                />
              </Form.Item>
              <Form.Item name="id" label="分区ID" className="ant-col ant-col-18">
                <Input
                  disabled
                  addonAfter={
                    <ConfigProvider
                      theme={{
                        components: {
                          Button: {
                            paddingInline: 0,
                          },
                        },
                      }}
                    >
                      <Tooltip title="点击复制ID">
                        <Button
                          style={{ marginLeft: '-8px' }}
                          type="text"
                          size="small"
                          icon={<CopyOutlined />}
                          onClick={() => {
                            navigator.clipboard.writeText(baseInfo.id?.toString() || '');
                            message.success('ID已复制');
                          }}
                        ></Button>
                      </Tooltip>
                    </ConfigProvider>
                  }
                />
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                name="name"
                label="设备名称"
                className="ant-col ant-col-18"
                rules={[{ required: true, message: '请输入设备名称' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="type"
                label="设备类型"
                className="ant-col ant-col-18"
                rules={[{ required: true, message: '请选择设备类型' }]}
              >
                <Select
                  disabled
                  options={[
                    { label: '一体柜', value: 1 },
                    { label: '电池箱', value: 2 },
                    { label: 'PCS', value: 3 },
                    { label: '电表', value: 4 },
                    { label: '变压器', value: 5 },
                    { label: '一体柜总控制器', value: 6 },
                    { label: '一体柜控制器', value: 7 },
                    { label: 'PCS控制器', value: 8 },
                    { label: '逆变器', value: 9 },
                    { label: '充电桩', value: 10 },
                  ]}
                />
              </Form.Item>
              <Form.Item
                name="model"
                label="设备型号"
                className="ant-col ant-col-18"
                rules={[{ required: true, message: '请选择设备型号' }]}
              >
                <Select
                  options={deviceModelList.map((model: DeviceModelVO) => ({
                    label: model.deviceModelName,
                    value: model.deviceId,
                  }))}
                />
              </Form.Item>
              {baseInfo.type === 4 && (
                <Form.Item
                  name="voltLevel"
                  label="电压等级"
                  className="ant-col ant-col-18"
                  rules={[{ required: true, message: '请选择电压等级' }]}
                >
                  <Select
                    options={voltLevels}
                    onChange={(value, option) => {
                      console.log('Selected value:', value);
                      console.log('Selected option:', option);
                    }}
                  />
                </Form.Item>
              )}
              <Form.Item name="code" label="设备编码" className="ant-col ant-col-18">
                <Input disabled />
              </Form.Item>
            </>
          )}
        </ProForm>
      )}
    </div>
  );
};

export default App;
